import Vue from "vue";
import VueRouter from "vue-router";
import Layout from "@/layout";
import store from "../store"; // 引入Vuex store
Vue.use(VueRouter);

// 定义路由
export const routes = [
  {
    path: "/login",
    component: () =>
      import(/* webpackChunkName: "login" */ "@/views/login/LoginView.vue"),
    hidden: true,
    meta: { title: "Login" },
  },
  {
    path: "/redirect",
    component: Layout,
    hidden: true,
    children: [
      {
        path: "/redirect/:path(.*)",
        component: () => import("@/views/redirect"),
      },
    ],
  },
  {
    path: "/select-hotel", // 酒店选择页面路由
    name: "HotelSelect",
    component: () => import("@/views/home/components/HotelSelector"),
    meta: { requiresAuth: true, icon: "" }, // 需要登录才能访问
    hidden: true,
  },
  // 2. Home (关键修复)
  {
    path: "",
    component: Layout,
    redirect: "/index", // 自动重定向到 /index
    children: [
      {
        path: "index", // ✅ 相对路径
        component: () => import("@/views/home/HomeView"),
        name: "Index",
        meta: {
          title: "Hotel Dashboard",
          icon: "dashboard",
          affix: true,
          noCache: true,
        },
      },
    ],
  },
  // {
  //   path: "/social-media",
  //   component: Layout,
  //   meta: { title: "Social Media", icon: "social" },
  //   alwaysShow: true,
  //   children: [
  //     {
  //       path: "",
  //       redirect: "feed",
  //       hidden: true,
  //     },
  //     {
  //       path: "analytics",
  //       component: () => import("@/views/socialMedia/index"),
  //       name: "SocialMediaAnalytics",
  //       meta: { title: "Analytics", icon: "social" },
  //     },
  //     {
  //       path: "feed",
  //       component: () => import("@/views/socialMedia/feed/index"),
  //       name: "SocialMediaFeed",
  //       meta: { title: "Feed", icon: "feed", affix: true },
  //     },
  //   ],
  // },
  // {
  //   path: "/restaurants-and-bars",
  //   component: Layout,
  //   meta: { title: "Restaurants & Bars", icon: "reviews" },
  //   alwaysShow: true,
  //   children: [
  //     {
  //       path: "",
  //       redirect: "bars",
  //       hidden: true,
  //     },
  //     {
  //       path: "bars",
  //       component: () => import("@/views/hotelRestaurantsBars/index"),
  //       name: "HotelRestaurantsBars",
  //       meta: { title: "Bars", icon: "reply" },
  //     },
  //   ],
  // },

  {
    path: "/reviews-and-reply",
    component: Layout,
    meta: { title: "Reviews & Reply", icon: "reviews" },
    children: [
      {
        path: "",
        component: () => import("@/views/ReviewsReply/index"),
        name: "ReviewsAndReply",
        meta: { title: "Reviews & Reply", icon: "reviews" },
      },
    ],
  },
  // {
  //   path: "/reviews-and-reply",
  //   component: Layout,
  //   meta: { title: "Reviews & Reply", icon: "reviews" },
  //   alwaysShow: true,
  //   children: [
  //     {
  //       path: "reply-template",
  //       component: () => import("@/views/ReviewsReply/index"),
  //       name: "ReviewsAndReply",
  //       meta: { title: "Reply Template", icon: "reply" },
  //     },
  //   ],
  // },
  // {
  //   path: "/competitors",
  //   component: Layout,
  //   children: [
  //     {
  //       path: "",
  //       component: () => import("@/views/competitors/index"),
  //       name: "Competitors",
  //       meta: { title: "Competitors", icon: "com" },
  //     },
  //   ],
  // },
  // {
  //   path: "/inside-out-staff-logs",
  //   component: Layout,
  //   children: [
  //     {
  //       path: "",
  //       component: () => import("@/views/staffLogs/index"),
  //       name: "InsideOutStaffLogs",
  //       meta: { title: "Inside-out Staff Logs", icon: "inside" },
  //     },
  //   ],
  // },
  // {
  //   path: "/crm-and-profiles",
  //   component: Layout,
  //   children: [
  //     {
  //       path: "",
  //       component: () => import("@/views/staffLogs/index"),
  //       name: "CRMAndProfiles",
  //       meta: { title: "CRM & Profiles", icon: "crm" },
  //     },
  //   ],
  // },
  // {
  //   path: "/reporting-tools",
  //   component: Layout,
  //   children: [
  //     {
  //       path: "",
  //       component: () => import("@/views/staffLogs/index"),
  //       name: "ReportingTools",
  //       meta: { title: "Reporting Tools", icon: "report" },
  //     },
  //   ],
  // },
  // {
  //   path: "/setting",
  //   component: Layout,
  //   children: [
  //     {
  //       path: "",
  //       component: () => import("@/views/setting/index"),
  //       name: "SettingAlerts",
  //       meta: { title: "Setting (Alerts)", icon: "set" },
  //     },
  //   ],
  // },
  // 404页面
  {
    path: "*", // 匹配所有未定义的路由
    component: Layout,
    hidden: true,
    children: [
      {
        path: "",
        component: () => import("@/views/error/404"),
        name: "NotFound",
        meta: { title: "404 Not Found", icon: "" },
      },
    ],
  },
];

// 创建路由实例
const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  strict: false,
  routes,
});

// 导航守卫 - 全局前置守卫
// 导航守卫 - 简化逻辑
// 全局前置守卫 - 优化版
router.beforeEach(async (to, from, next) => {
  // 强制去除URL末尾斜杠（根路径/除外）
  if (to.path.endsWith("/") && to.path !== "/") {
    const newPath = to.path.slice(0, -1); // 去除末尾斜杠
    next(newPath + (to.search || "") + (to.hash || ""));
    return;
  }

  // 记录开始导航的时间，用于性能监控
  const start = Date.now();

  // 从Vuex获取认证状态（推荐使用Vuex而非直接操作localStorage）
  const isAuthenticated = store.getters["auth/isAuthenticated"];

  // 白名单路由 - 不需要登录即可访问的路由
  const whiteList = ["/login", "/redirect"];

  try {
    // 1. 检查是否需要重定向到登录页
    if (!isAuthenticated && !whiteList.includes(to.path)) {
      // 未登录且访问需要权限的页面，重定向到登录页
      next({
        path: "/login",
        query: { redirect: to.fullPath },
      });
      return;
    }

    // 2. 已登录但访问登录页，重定向到首页
    if (isAuthenticated && to.path === "/login") {
      next({ path: "/" });
      return;
    }

    // 3. 已登录且访问需要权限的页面，正常进入
    next();
  } catch (error) {
    console.error("路由导航错误:", error);
    // 导航错误时重定向到登录页或显示错误页面
    next({ path: "/login", query: { error: "navigation" } });
  } finally {
    // 导航结束后的性能日志
    console.log(`路由导航耗时: ${Date.now() - start}ms`, {
      from: from.path,
      to: to.path,
    });
  }
});

export default router;
